package cn.mesmile.shiro.module.jwt;

import cn.mesmile.shiro.module.permission.entity.Permission;
import cn.mesmile.shiro.module.role.dto.RoleVo;
import cn.mesmile.shiro.module.user.dto.UserVo;
import cn.mesmile.shiro.module.user.entity.User;
import cn.mesmile.shiro.module.user.service.UserService;
import cn.mesmile.shiro.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zb
 * @date 2021/2/21 13:12
 * @Description:
 */
public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 限定这个 Realm 只处理我们自定义的 JwtToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 此处的 SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        System.out.println(">>>>>>>>>>>>>  进入到认证 JwtRealm");

        JwtToken jwtToken = (JwtToken) authcToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AccountException("JWT token参数异常！");
        }
        // 从 JwtToken 中获取当前用户
        String username = jwtToken.getPrincipal().toString();
        // 从数据库获取密码
        User user = userService.findUserInfoByUsername(username);

        // 用户不存在
        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }

        // 用户被锁定
//        if (user.getLocked()) {
//            throw new LockedAccountException("该用户已被锁定,暂时无法登录！");
//        }


        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, username, getName());

        // 设置【盐】
        info.setCredentialsSalt(ByteSource.Util.bytes("aerofugia"));
        return info;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> 进入到授权  JwtRealm");
        // 获取到身份信息
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
        User newUser = (User) primaryPrincipal;
        UserVo userVo = userService.findAllUserInfoByUsername(newUser.getUsername());
        List<RoleVo> roleList = userVo.getRoleList();
        // 从数据库中获取到[权限]
        Set<String> permissions = new HashSet<>();
        // 从数据获取【角色】
        Set<String> roles = new HashSet<>(roleList.size());

        roleList.forEach(roleVo -> {

            List<Permission> permissionList = roleVo.getPermissionList();
            String roleName = roleVo.getName();
            roles.add(roleName);

            permissionList.forEach(permission -> {
                String name = permission.getName();
                permissions.add(name);
            });

        });


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);

        return simpleAuthorizationInfo;
    }

}
